import { useCallback } from 'react';
import { Alert, AlertButton, Linking } from 'react-native';

import { VersionAPI } from '@/api/versionAPI';
import { APP_STORE_URL } from '@/constants';

/**
 * TODO: 实现强制更新功能
 * @returns
 */
const useForcedUpdate = () => {
  /**
   * 强制更新
   */
  const checkForcedUpdate = () => {
    VersionAPI.check().then((res) => {
      if (res.code === 0) {
        const { needUpdate, title, updateInfo, forceUpDate } = res.data;
        if (needUpdate) {
          // 强制更新
          showAlert(forceUpDate, title, updateInfo);
        }
      } else {
        console.warn('版本检测失败');
      }
    });
  };

  const showAlert = useCallback((force: boolean, title: string, info: string) => {
    const cancel: AlertButton = {
      text: 'Cancel',
      onPress: () => console.log('取消被点击'),
      style: 'cancel',
    };
    const update: AlertButton = {
      text: 'Update',
      onPress: async () => {
        const canOpen = await Linking.canOpenURL(APP_STORE_URL);
        if (canOpen) {
          // 打开App Store
          Linking.openURL(APP_STORE_URL).then(() => {
            showAlert(force, title, info);
          });
        } else {
          console.log('无法打开App Store');
        }
      },
      style: 'destructive',
    };

    if (force) {
      Alert.alert(title, info, [update]);
    } else {
      Alert.alert(title, info, [cancel, update]);
    }
  }, []);

  return {
    checkForcedUpdate,
  };
};
export default useForcedUpdate;
